package com.jinlejia.erp.ui.house.prospect;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchHouseCoreSellAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BeanKey;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.BuildingBean;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.RoomBean;
import com.jinlejia.erp.bean.UnitBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.FragmentSearchCoreListBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * @author SongJiaTai
 * @description:查询出售核心结果
 * @date :2019/7/9 20:42
 */
public class SeachCoreSellListFragment extends Fragment {


    SearchHouseCoreSellAdapter adapter;

    CallBackValue callBackValue;

    /**
     * fragment与activity产生关联是  回调这个方法
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue =(CallBackValue) getActivity();
    }

    public SeachCoreSellListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    private FragmentSearchCoreListBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_search_core_list, container, false);
        binding = DataBindingUtil.bind(view);
        return view;
    }

    private SearchHelper helper;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.bind(view);
        helper = new SearchHelper(getContext());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.addItemDecoration(new RecycleViewDivider(
                getContext(), LinearLayoutManager.HORIZONTAL, 1, getActivity().getResources().getColor(R.color.colorDivider)));
        binding.recyclerView.setHasFixedSize(true);
        ArrayList list = new ArrayList();
        adapter = new SearchHouseCoreSellAdapter(list, "");
        binding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((view1, o) -> {
            BeanKey key = (BeanKey) o;
            if (key instanceof EstateBean){
                //房屋名称
                callBackValue.houseNameValue(key.toString(),key.key());
            }else if (key instanceof BuildingBean){
                //座栋号
                callBackValue.houseBuildValue(key.toString(),key.key());
            }else if (key instanceof UnitBean){
                //单元号
                callBackValue.houseUnitValue(key.toString(),key.key());
            }else if (key instanceof RoomBean){
                //房间号
                callBackValue.houseRoomValue(key.toString(),key.key());
            }

        });
    }
    public static final int TYPE_HOUSE_NAME = 0;
    public static final int TYPE_HOUSE_BUILDING = 1;
    public static final int TYPE_HOUSE_UNIT = 2;
    public static final int TYPE_HOUSE_ROOM = 3;
    public void inputText(int type,String data) {
        switch (type){
            case TYPE_HOUSE_NAME:
                searchHouseName(data);
                break;

        }
    }

    public void inputText(int type,String code,String data){
        switch (type){
            case TYPE_HOUSE_BUILDING:
                searchBuilding(code,data);
                break;
            case TYPE_HOUSE_UNIT:
                searchUnit(code,data);
                break;
            case TYPE_HOUSE_ROOM:
                searchRoom(code,data);
                break;
        }
    }

    private HashMap<String,List<BuildingBean>> cacheBuilding;
    private void searchBuilding(final String reCode, final String data){
        if (cacheBuilding==null){
            cacheBuilding = new HashMap<>();
        }
        List<BuildingBean> list = cacheBuilding.get(reCode);
        if (list!=null && list.size()>0){
            sort(data,list);
            return;
        }
        if (helper==null){
            helper = new SearchHelper(getContext());
        }
        helper.queryBuildingList(reCode, beans -> {
            if (beans==null)return;
            cacheBuilding.put(reCode,beans);
            sort(data,beans);
        });
    }

    private HashMap<String,List<UnitBean>> cacheUnit;
    private void searchUnit(final String code, final String data){
        if (cacheUnit==null){
            cacheUnit = new HashMap<>();
        }
        List<UnitBean> list = cacheUnit.get(code);
        if (list!=null && list.size()>0){
            sort(data,list);
            return;
        }
        helper.queryEstateListByBuildingCode(code, beans -> {
            if (beans==null)return;
            cacheUnit.put(code,beans);
            sort(data,beans);
        });
    }



    private HashMap<String,List<RoomBean>> cacheRoom;
    private void searchRoom(final String code,final String data){
        if (cacheRoom==null){
            cacheRoom = new HashMap<>();
        }
        List<RoomBean> list = cacheRoom.get(code);
        if (list!=null && list.size()>0){
            sort(data,list);
            return;
        }
        helper.queryEstateListByUnitCode(code, beans -> {
            if (beans != null) {
                cacheRoom.put(code,beans);
                sort(data,beans);
            }
        });
    }

    private void searchHouseName(final String searchTxt ) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reNameLike", searchTxt);
        OkHttpUtils.postString()
                .url(ApiConfig.HOUSE_SOURCE_QUERYE_STATE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        CustomToast.showToast(getActivity(), "网络连接失败", 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getContext(), response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            JSONArray list = data.getJSONArray("realEstateList");
                            ArrayList<EstateBean> beans = (ArrayList<EstateBean>) JSON.parseArray(list.toString(), EstateBean.class);
                            adapter.setWord(searchTxt);
                            adapter.setData(beans);
                        }
                    }
                });
    }

    //排序
    private <T extends BeanKey> void sort(final String data, List<T> beans){
        if (beans!=null){
            List<T> sortList = new ArrayList<>(beans);
            Collections.sort(sortList, (o1, o2) -> {
                String o1Text = o1.toString();
                String o2Text = o2.toString();
                int o1TextIndex = o1Text.indexOf(data);
                int o2TextIndex = o2Text.indexOf(data);
                return o2TextIndex-o1TextIndex;
            });
            List<T> newList = new ArrayList<>();
            for (T t:sortList) {
                if (t.toString().contains(data)){
                    newList.add(t);
                }else {
                    break;
                }
            }
            adapter.setWord(data);
            adapter.setData((ArrayList) newList);
        }
    }

    //定义一个回调接口
    public interface CallBackValue{
        void houseNameValue(String strValue, String code);
        void houseBuildValue(String value, String code);

        void houseUnitValue(String value, String code);
        void houseRoomValue(String value, String code);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding.unbind();
        EventBus.getDefault().unregister(this);
    }


}
